﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myTwitter.BO;
using Expression.Blend.SampleData.SampleDataSource;
using System.Windows.Threading;
using System.ComponentModel;
using myTwitter.BO.Search;
using System.Xml.Linq;
using System.IO;
using System.Threading;

namespace myTwitter.API
{
    public class Test_TwitterProvider : ITwitterProvider
    {
        private List<DirectMessage> _directMessages;
        private List<Status> _friendsStatus;
        
        private SampleDataSource _sampleDataSource = new SampleDataSource();
        private Random _random = new Random();
        public Exception LastException { get; set; }
        
        private string _login;
        private string _password;
        private UserOAuthenSettings _currentUserOAuthenSettings;

        #region ITwitterProvider Members

        public event IMessagesUpdateErrorHandler IMessagesUpdateError;
        public event DirectMessagesUpdatedHandler DirectMessagesUpdated;
        public event StatusUpdatedHandler StatusUpdated;
        public event MentionsUpdatedHandler MentionsUpdated;
        public event ConnectedUserInfoUpdatedHandler ConnectedUserInfoUpdated;
        public event UserInfoUpdatedHandler UserInfoUpdated;
        public event TrendsUpdatedHandler TrendsUpdated;

        public string Login
        {
            get
            {
                return _login;
            }
            set
            {
                _login = value;
            }
        }

        public string Password
        {
            get
            {
                return _password;
            }
            set
            {
                _password = value;
            }
        }

        public UserOAuthenSettings CurrentUserOAuthenSettings
        {
            get { return _currentUserOAuthenSettings; }
            set { _currentUserOAuthenSettings = value; }
        }

        public void UpdateStatus(string status)
        {
            UpdateStatus(status, -1);
        }

        public void UpdateStatus(string status, long inReplyToStatusId)
        {
            Status s = new Status();
            s.Text = status;
            s.ID = 210392;
            s.Source = "sdofjdsof";
            s.Truncated = false;
            s.CreatedAt = DateTime.Now;
            s.User = new User()
            {
                Name = "Yann",
                ProfileImageUrl = "http://s3.amazonaws.com/twitter_production/profile_images/73471615/me_normal.png"
            };
            _friendsStatus.Add(s);
        }

        public void UpdateStatusAsync(string status)
        {
            
        }

        public void UpdateStatusAsync(string status, long inReplyToStatusId)
        {
            

        }

        /// <summary>
        /// Ends the session of the authenticating user, returning a null cookie.
        /// Use this method to sign users out of client-facing applications like widgets.
        /// </summary>
        public void EndSession()
        {
            
        }

        public void StopAutoRefresh()
        {
        }

        public string SendDirectMessage(string user, string text)
        {
            throw new NotImplementedException();
        }

        public List<myTwitter.BO.DirectMessage> GetDirectMessages()
        {
            GlobalController.Log("In RefreshDirectMessages()");
            if (_directMessages == null)
            {
                _directMessages = new List<DirectMessage>();
                for (int i = 0; i < _sampleDataSource.DirectMessages.Count; i++)
                {
                    DirectMessage dm = new DirectMessage();
                    dm.CreatedAt = GetRandomDate();
                    dm.ID = _random.Next(0, 20);
                    dm.InReplyToUser = GetNewUser();
                    dm.Recipient = GetNewUser();
                    dm.RecipientScreenName = dm.Recipient.ScreenName;
                    dm.Sender = GetNewUser();
                    dm.SenderScreenName = _sampleDataSource.DirectMessages[i].Name;
                    dm.Text = _sampleDataSource.DirectMessages[i].Text;
                    dm.User = GetNewUser();
                    _directMessages.Add(dm);
                }
            }
            GlobalController.Log("Out RefreshDirectMessages()");
            return _directMessages;
        }

        public List<myTwitter.BO.DirectMessage> GetSentDirectMessages()
        {
            throw new NotImplementedException();
        }

        public List<myTwitter.BO.Status> GetMentions()
        {
            GlobalController.Log("In GetMentions()");

            List<Status> mentions = new List<Status>();
            {
                for (int i = 0; i < 20; i++)
                {
                    Status s = new Status();
                    s.Text = i.ToString() + " - Hello @yannalet, I like your web site !";
                    s.ID = _random.Next(0, 1000);
                    s.Source = "Test Twitter Provider";
                    s.Truncated = false;
                    s.CreatedAt = DateTime.Now;
                    s.IsMention = true;
                    s.User = new User()
                    {
                        Name = "Tom",
                        ProfileImageUrl = "http://static.twitter.com/images/default_profile_normal.png"
                    };
                    mentions.Add(s);
                }
            }
            GlobalController.Log("Out GetMentions()");
            return mentions;
        }

        public List<myTwitter.BO.Status> GetFriendStatus()
        {
            GlobalController.Log("In GetFriendStatus()");
            if (_friendsStatus == null)
            {
                _friendsStatus = new List<Status>();
                for (int i = 0; i < 20; i++)
                {
                    Status s = new Status();
                    s.Text = i.ToString()+" - This is my wonderful web site : http://www.yannalet.com check it out !";
                    s.ID = _random.Next(0,100);
                    s.Source = "sdofjdsof";
                    s.Truncated = false;
                    s.CreatedAt = GetRandomDate();
                    s.User = new User()
                    {
                        Name = "Yann",
                        ProfileImageUrl = "http://s3.amazonaws.com/twitter_production/profile_images/73471615/me_normal.png"
                    };
                    _friendsStatus.Add(s);
                }
            }
            GlobalController.Log("Out GetFriendStatus()");
            return _friendsStatus;
        }

        public myTwitter.BO.User GetUser(string userScreenName)
        {
            User user = new User()
            {
                Name = "Yann ALET",
                ScreenName = "yannalet",
                StatusesCount = 2309,
                Url = "http://www.yannalet.com",
                ID = 02830394830,
                FollowersCount = 294,
                Following = false,
                FriendsCount = 35,
                Location = "Paris",
                Description = "WPF Developper",
                ProfileImageUrl = "http://s3.amazonaws.com/twitter_production/profile_images/73471615/me_normal.png",
                Status = new Status() 
                {
                    Text = "@Diraen Nous on est chez GoDaddy, ca marche bien les premiers prix sont assez interressants. Patrick m'a recommandé OVH aussi.",
                    CreatedAt = DateTime.Now
                }
            };
            return user;
        }

        public List<User> GetFollowers(string userScreenName, string cursorId)
        {
            return new List<User>();
        }

        public void VerifyCredential()
        {
            if(VerifyCredentialCompleted!=null)
                VerifyCredentialCompleted(GetNewUser());
        }

        public void Follow(User userID)
        {
        }

        public void UnFollow(User userID)
        {
        }

        private User GetNewUser()
        {
            User user = new User();
            user.Name = "Yann ALET";
            user.ProfileImageUrl = "http://s3.amazonaws.com/twitter_production/profile_images/73471615/me_normal.png";
            return user;
        }

        private DateTime GetRandomDate()
        {
            int year = _random.Next(1990, 2009);
            int month = _random.Next(1, 12);
            int day = _random.Next(1, 25);
            return new DateTime(year, month, day);
        }

        public void RefreshStatus()
        {
            List<Status> friendsStatus = GetFriendStatus();
            StatusUpdated(friendsStatus);
        }

        public void RefreshDirectMessages()
        {
            List<DirectMessage> receivedDirectMessages = GetDirectMessages();
            
            if (DirectMessagesUpdated != null)
                DirectMessagesUpdated(receivedDirectMessages);
        }

        

        #endregion

        #region ITwitterProvider Members


        public void RefreshStatus(TimeSpan autoRefreshInterval)
        {
            DispatcherTimer refreshTimer = new DispatcherTimer();
            refreshTimer.Interval = new TimeSpan(0,1,10);
            refreshTimer.Tick += new EventHandler(delegate(object sender, EventArgs e)
                {
                    RefreshStatus();
                });
            refreshTimer.Start();
            RefreshStatus();
        }

        public void RefreshDirectMessages(TimeSpan autoRefreshInterval)
        {
            DispatcherTimer refreshTimer = new DispatcherTimer();
            refreshTimer.Interval = new TimeSpan(0, 1, 10);
            refreshTimer.Tick += new EventHandler(delegate(object sender, EventArgs e)
            {
                RefreshDirectMessages();
            });
            refreshTimer.Start();
            RefreshDirectMessages();
        }

        #endregion

        #region ITwitterProvider Members


        public void RefreshMentions()
        {
            List<Status> mentions = GetMentions();
            DispatcherTimer delayTimer = new DispatcherTimer();
            delayTimer.Tick += new EventHandler(delegate(object sender, EventArgs e)
                {
                    delayTimer.Stop();
                    GlobalController.Log("Calling MentionsUpdated");
                    MentionsUpdated(mentions);
                });
            delayTimer.Interval = new TimeSpan(0, 0, 5);
            delayTimer.Start();            
        }

        public void RefreshMentions(TimeSpan autoRefreshInterval)
        {
            DispatcherTimer refreshTimer = new DispatcherTimer();
            refreshTimer.Interval = new TimeSpan(0, 0, 15);
            refreshTimer.Tick += new EventHandler(delegate(object sender, EventArgs e)
            {
                RefreshMentions();
            });
            refreshTimer.Start();
            RefreshMentions();
        }

        public void RefreshConnectedUserInfo()
        {
            User user = GetUser(Login);
            ConnectedUserInfoUpdated(user);
        }

        public void RefreshUserInfo(TimeSpan autoRefreshInterval)
        {
            DispatcherTimer refreshTimer = new DispatcherTimer();
            refreshTimer.Interval = new TimeSpan(0, 1, 10);
            refreshTimer.Tick += new EventHandler(delegate(object sender, EventArgs e)
            {
                RefreshConnectedUserInfo();
            });
            refreshTimer.Start();
            RefreshConnectedUserInfo();
        }

        public void RefreshTrends()
        {
        }

        public void RefreshTrends(TimeSpan autoRefreshInterval)
        {
        }

        public void GetAuthorizationCode()
        {
            
        }

        public UserOAuthenSettings Authorize(string code)
        {
            return null;
        }

        public Tweets GetUserTweets(User user)
        {
            return null;
        }

        public Relationship GetRelationship(User targetUser)
        {
            return null;
        }

        public List<User> GetFriends(string userScreenName, string cursorId)
        {
            return new List<User>();
        }

        #endregion

        #region ITwitterProvider Members


        public void Search(string query)
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(delegate(object sender, DoWorkEventArgs e)
            {
                List<IMessage> results = new List<IMessage>();
                for (int i = 0; i < 10; i++)
                {
                    Entry entry = new Entry()
                        {
                            Id = Guid.NewGuid().ToString(),
                            LinkUrl = Guid.NewGuid().ToString(),
                            Title = Guid.NewGuid().ToString(),
                            Content = Guid.NewGuid().ToString(),
                            ImageUrl = GetRandomImagePath(),
                            //TwitterSource = element.Element(nsatom + "source").Value,
                            //TwitterLanguage = element.Element(nsatom + "lang").Value,
                            Author = new Author()
                            {
                                Name = Guid.NewGuid().ToString(),
                                Uri = Guid.NewGuid().ToString()
                            }
                        };
                    results.Add(entry);
                }
                
                e.Result = results;
            });
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    if (IMessagesUpdateError != null)
                        IMessagesUpdateError(e.Error);
                }
                else
                {
                    if (SearchCompleted != null)
                        SearchCompleted(e.Result as List<IMessage>);
                }
            });
            bw.RunWorkerAsync();
        }

        string GetRandomImagePath()
        {
            DirectoryInfo di = new DirectoryInfo(@"C:\Users\Public\Pictures\Sample Pictures");
            FileInfo[] files = di.GetFiles("*.jpg");
            return files[_random.Next(0, files.Length - 1)].FullName;
        }

        #endregion

        #region ITwitterProvider Members


        public event SearchCompletedHandler SearchCompleted;

        #endregion

        #region ITwitterProvider Members


        public event VerifyCredentialCompletedHandler VerifyCredentialCompleted;

        #endregion

        
    }
}
